package com.micro.ai.auth.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.auth.dto.UserSessionDTO;
import com.micro.ai.auth.service.UserSessionService;
import com.micro.ai.commons.domain.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.micro.ai.auth.annotation.AuditLogAnnotation;
import java.util.List;
import java.util.Map;

/**
 * 用户会话控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/sessions")
@Tag(name = "会话管理", description = "用户会话查询、强制下线等操作")
public class UserSessionController {

    @Autowired
    private UserSessionService userSessionService;

    /**
     * 获取当前用户所有会话
     */
    @GetMapping
    @Operation(summary = "获取我的会话", description = "查询当前用户所有活跃会话")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权")
    })
    public ApiResponse<List<UserSessionDTO>> getMySessions(@RequestAttribute("userId") String userId) {
        log.info("查询用户会话: userId={}", userId);
        List<UserSessionDTO> sessions = userSessionService.getUserSessions(userId);
        return ApiResponse.success(sessions);
    }

    /**
     * 获取会话详情
     */
    @GetMapping("/{sessionId}")
    @Operation(summary = "获取会话详情", description = "根据会话ID获取详细信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = UserSessionDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "会话不存在")
    })
    public ApiResponse<UserSessionDTO> getSessionById(
            @Parameter(description = "会话ID", required = true) @PathVariable String sessionId) {
        UserSessionDTO session = userSessionService.getSessionById(sessionId);
        return ApiResponse.success(session);
    }

    /**
     * 强制下线指定会话
     */
    @DeleteMapping("/{sessionId}")
    @Operation(summary = "下线会话", description = "强制下线指定会话")
    @AuditLogAnnotation(action = "DELETE", resourceType = "SESSION", description = "强制下线会话")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "下线成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限或不能下线其他用户会话"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "会话不存在")
    })
    public ApiResponse<Void> terminateSession(
            @Parameter(description = "会话ID", required = true) @PathVariable String sessionId,
            @RequestAttribute("userId") String currentUserId) {
        log.info("下线会话: sessionId={}, userId={}", sessionId, currentUserId);
        userSessionService.terminateSession(sessionId, currentUserId);
        return ApiResponse.successVoid("会话已下线");
    }

    /**
     * 强制下线所有会话（除当前）
     */
    @DeleteMapping("/all")
    @Operation(summary = "下线所有会话", description = "强制下线当前用户的所有其他会话（保留当前会话）")
    @AuditLogAnnotation(action = "DELETE", resourceType = "SESSION", description = "强制下线所有会话")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "下线成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权")
    })
    public ApiResponse<Void> terminateAllSessions(
            @RequestAttribute("userId") String userId,
            @Parameter(description = "当前会话ID") @RequestParam(required = false) String currentSessionId) {
        log.info("下线所有会话: userId={}, currentSessionId={}", userId, currentSessionId);
        userSessionService.terminateAllSessions(userId, currentSessionId);
        return ApiResponse.successVoid("所有其他会话已下线");
    }

    /**
     * 分页查询在线会话（管理员）
     */
    @GetMapping("/online")
    @PreAuthorize("hasAuthority('session:view')")
    @Operation(summary = "查询在线会话", description = "分页查询所有在线会话（管理员）")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Page<UserSessionDTO>> listOnlineSessions(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "关键词（用户ID/IP/位置）") @RequestParam(required = false) String keyword) {
        Page<UserSessionDTO> page = userSessionService.listOnlineSessions(pageNum, pageSize, tenantId, keyword);
        return ApiResponse.success(page);
    }

    /**
     * 获取在线统计（管理员）
     */
    @GetMapping("/stats")
    @PreAuthorize("hasAuthority('session:view')")
    @Operation(summary = "在线统计", description = "统计在线会话数、在线用户数等（管理员）")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Map<String, Object>> getOnlineStats(
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId) {
        Map<String, Object> stats = userSessionService.getOnlineStats(tenantId);
        return ApiResponse.success(stats);
    }

    /**
     * 清理过期会话（管理员）
     */
    @DeleteMapping("/expired")
    @PreAuthorize("hasAuthority('session:manage')")
    @Operation(summary = "清理过期会话", description = "清理所有已过期的会话记录（管理员）")
    @AuditLogAnnotation(action = "DELETE", resourceType = "SESSION", description = "清理过期会话")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "清理成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Integer> cleanExpiredSessions() {
        log.info("清理过期会话");
        int count = userSessionService.cleanExpiredSessions();
        return ApiResponse.success(count);
    }
}

